package com.wjf.accesscontrol.ui.setting

import androidx.lifecycle.ViewModel
import androidx.lifecycle.liveData
import com.wjf.accesscontrol.net.api.ApiHelper
import com.wjf.accesscontrol.net.api.RetrofitBuilder
import com.wjf.accesscontrol.net.api.RetrofitBuilder.getRequestBody
import com.wjf.accesscontrol.net.utils.Resource
import com.wjf.accesscontrol.util.Constant
import com.wjf.accesscontrol.util.LogUtils
import com.wjf.accesscontrol.util.md5
import org.json.JSONObject

/**
 * @Description
 * @Author WuJianFeng
 * @Date 2024/2/1 14:44
 *
 */

class SettingViewModel: ViewModel() {

    fun login(add: String, phone: String, password: String) = liveData {
        Constant.serviceId = ""
        Constant.serviceMethod = ""
        emit(Resource.loading(data = null))
        try {
            val jsonObject = JSONObject()
            try {
                jsonObject.put("account",phone)
                jsonObject.put("passwd",password.md5())
                jsonObject.put("usr","manage")
                jsonObject.put("ccd","KHDLX-PC")
                jsonObject.put("loginModel","1")
            } catch (e: Exception) {
                LogUtils.d("__err-login", "${e.message}")
            }

            emit(
                Resource.success(baseBean = ApiHelper.login("${add}auth/login",
                    RetrofitBuilder.getRequestBody(jsonObject.toString())
                )))
        } catch (exception: Exception) {
            LogUtils.d("__exception","${exception.message}")
            emit(Resource.error(data = null, message = exception.message ?: "Error Occurred!"))
        }
    }

    fun stationDetail(machineId: String,url: String) = liveData {
        emit(Resource.loading(data = null))
        try {
            Constant.serviceId = "station"
            Constant.serviceMethod = "stationDetail"

            emit(Resource.success(baseBean = ApiHelper.stationDetail(url, machineId)))
        } catch (exception: Exception) {
            LogUtils.d("__exception","${exception.message}")
            emit(Resource.error(data = null, message = exception.message ?: "Error Occurred!"))
        }
    }

    /**
     * 激活站点
     */
    fun deviceMachine(machineId: String,url: String) = liveData {
        emit(Resource.loading(data = null))
        try {
            Constant.serviceId = "device"
            Constant.serviceMethod = "deviceMachine"

            val jsonObject = JSONObject()
            try {
                jsonObject.put("machineId",machineId)
            } catch (e: Exception) {
                LogUtils.d("__err-deviceMachine", "${e.message}")
            }
            emit(Resource.success(baseBean = ApiHelper.deviceMachine(url,getRequestBody(jsonObject.toString()))))
        } catch (exception: Exception) {
            LogUtils.d("__exception","${exception.message}")
            emit(Resource.error(data = null, message = exception.message ?: "Error Occurred!"))
        }
    }

}